import 'package:flower/pages/tabs/detail/flower_detail.dart';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:flutter/widgets.dart';

import '../../../../components/cached_image_widget.dart';
import '../../../../config/service_url.dart';

import '../../../../model/flower_list.dart';
import '../../../../utils/http_util.dart';
import '../../../../utils/my_colors.dart';
import '../../../../utils/my_icons.dart';
import '../../../../utils/self_screen_adaptor.dart';

class SearchFlower extends StatefulWidget {
  final String? keyword;
  const SearchFlower({super.key, this.keyword});

  @override
  State<SearchFlower> createState() => _SearchFlower();
}

class _SearchFlower extends State<SearchFlower> {
  List<FlowerData> flowerList = [];
  ScrollController scrollController = ScrollController();
  final TextEditingController _searchController = TextEditingController();
  @override
  void initState() {
    super.initState();
    queryFlowerList();
  }

  //获取花卉总的数据
  void queryFlowerList() async {
    Map<String, dynamic> map = <String, dynamic>{};
    map["keyword"] = widget.keyword;

    Response result =
        await HttpUtil.get(getFlowerByNameLike, queryParameters: map);
    FlowerListModel flowerListModel = FlowerListModel.fromJson(result.data);
    setState(() {
      flowerList = flowerListModel.data!;
    });
  }

  @override
  Widget build(BuildContext context) {
    SelfScreenAdaptor.init(context);
    return Scaffold(
      appBar: AppBar(
        title: const Text("搜索结果"),
        titleTextStyle: const TextStyle(fontSize: 16, color: MyColors.normal),
        centerTitle: true,
      ),
      body: ListView(controller: scrollController, children: <Widget>[
        search(),
        curated(),
      ]),
    );
  }

  //搜索
  Widget search() {
    return Container(
      margin: const EdgeInsets.all(9.0),
      padding: const EdgeInsets.symmetric(horizontal: 10.0),
      decoration: BoxDecoration(
        color: MyColors.white,
        border: Border.all(color: MyColors.border), // 添加灰色边框
        borderRadius: BorderRadius.circular(20.0),
      ),
      child: Stack(
        children: <Widget>[
          Positioned(
            child: TextField(
              controller: _searchController,
              decoration: const InputDecoration(
                labelText: '搜索',
                labelStyle: TextStyle(fontSize: 14.0), // 调整标签文本大小
                border: InputBorder.none, // 去掉边框
                contentPadding: EdgeInsets.symmetric(
                    vertical: 0.0, horizontal: 7.0), // 调整内边距以改变高度
              ),
              keyboardType: TextInputType.text, // 设置输入类型
              style: const TextStyle(fontSize: 14.0), // 可选：调整字体大小以进一步减小高度
            ),
          ),
          Container(
              alignment: Alignment.topRight,
              padding: const EdgeInsets.only(left: 260.0, top: 10.0),
              child: InkWell(
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => SearchFlower(
                        keyword: _searchController.value.text,
                      ),
                    ),
                  );
                },
                child: const Icon(
                  MyIcons.search,
                  color: MyColors.girlBlue,
                  size: 28,
                ),
              )),
        ],
      ),
    );
  }

  Widget curated() {
    return GridView.builder(
      padding: const EdgeInsets.all(10),
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      // 禁止GridView滚动，使用ListView的滚动
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2, // 每行两列
        crossAxisSpacing: 5.0,
        mainAxisSpacing: 5.0,
        childAspectRatio: 0.9, // 调整宽高比以适应内容
      ),
      itemCount: flowerList.length,
      itemBuilder: (context, index) {
        return GestureDetector(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) =>
                    FlowerDetailPage(flowerId: flowerList[index].id),
              ),
            );
          },
          child: Card(
            elevation: 3,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                  child: ClipRRect(
                    borderRadius:
                        const BorderRadius.vertical(top: Radius.circular(10)),
                    child: CachedImageWidget(
                      double.infinity,
                      double.infinity,
                      flowerList[index].coverUrl,
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        flowerList[index].name,
                        style: const TextStyle(
                            fontSize: 16, fontWeight: FontWeight.bold),
                      ),
                      const SizedBox(height: 5),
                      Text(
                        flowerList[index].ename,
                        style: const TextStyle(
                          fontSize: 14,
                          color: MyColors.ename,
                        ),
                      ),
                      const SizedBox(height: 5),
                      Text(
                        "￥${flowerList[index].price}",
                        style: const TextStyle(fontSize: 14, color: MyColors.red),
                      ),
                      const SizedBox(height: 5),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
